<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>为随机数生成器置种 - The Rust Rand Book</title>
        
        


        <!-- Custom HTML head -->
        


        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="Extended documentation for Rust&#x27;s Rand lib">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        
        <link rel="icon" href="favicon.svg">
        
        
        <link rel="shortcut icon" href="favicon.png">
        
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        
        <link rel="stylesheet" href="fonts/fonts.css">
        

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        

        
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="intro.html">介绍</a></li><li class="chapter-item expanded "><a href="guide-start.html"><strong aria-hidden="true">1.</strong> 入门指南</a></li><li class="chapter-item expanded "><a href="crates.html"><strong aria-hidden="true">2.</strong> crate 和特性</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="crates-rand.html"><strong aria-hidden="true">2.1.</strong> 随机加密(co)</a></li><li class="chapter-item expanded "><a href="crates-gen.html"><strong aria-hidden="true">2.2.</strong> 随机信号生成器</a></li></ol></li><li class="chapter-item expanded "><a href="guide.html"><strong aria-hidden="true">3.</strong> 指南</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="guide-data.html"><strong aria-hidden="true">3.1.</strong> 随机数据</a></li><li class="chapter-item expanded "><a href="guide-gen.html"><strong aria-hidden="true">3.2.</strong> 生成器类型</a></li><li class="chapter-item expanded "><a href="guide-rngs.html"><strong aria-hidden="true">3.3.</strong> 随机数生成器(RNGs)</a></li><li class="chapter-item expanded "><a href="guide-seeding.html" class="active"><strong aria-hidden="true">3.4.</strong> 为随机数生成器置种</a></li><li class="chapter-item expanded "><a href="guide-values.html"><strong aria-hidden="true">3.5.</strong> 随机值</a></li><li class="chapter-item expanded "><a href="guide-dist.html"><strong aria-hidden="true">3.6.</strong> 各种分布方式</a></li><li class="chapter-item expanded "><a href="guide-seq.html"><strong aria-hidden="true">3.7.</strong> 序列</a></li><li class="chapter-item expanded "><a href="guide-err.html"><strong aria-hidden="true">3.8.</strong> 错误处理</a></li></ol></li><li class="chapter-item expanded "><a href="portability.html"><strong aria-hidden="true">4.</strong> 可移植性</a></li><li class="chapter-item expanded "><a href="update.html"><strong aria-hidden="true">5.</strong> 更新</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="update-0.5.html"><strong aria-hidden="true">5.1.</strong> 更新到 0.5</a></li><li class="chapter-item expanded "><a href="update-0.6.html"><strong aria-hidden="true">5.2.</strong> 更新到 0.6</a></li><li class="chapter-item expanded "><a href="update-0.7.html"><strong aria-hidden="true">5.3.</strong> 更新到 0.7</a></li></ol></li><li class="chapter-item expanded "><a href="contributing.html"><strong aria-hidden="true">6.</strong> 贡献</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="contrib-doc.html"><strong aria-hidden="true">6.1.</strong> 文档</a></li><li class="chapter-item expanded "><a href="contrib-scope.html"><strong aria-hidden="true">6.2.</strong> Scope</a></li><li class="chapter-item expanded "><a href="contrib-test.html"><strong aria-hidden="true">6.3.</strong> 测试</a></li><li class="chapter-item expanded "><a href="contrib-bench.html"><strong aria-hidden="true">6.4.</strong> 基准</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                
                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                        
                    </div>

                    <h1 class="menu-title">The Rust Rand Book</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                        
                    </div>
                </div>

                
                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1><a class="header" href="#seeding-rngs" id="seeding-rngs">Seeding RNGs</a></h1>
<h1><a class="header" href="#为png置种seeding" id="为png置种seeding">为PNG置种(seeding)</a></h1>
<blockquote>
<p><a href="https://github.com/rust-random/book/blob/master/src/guide-seeding.md">guide-seeding.md</a><br />
commit: 3a691b0591512642e84ebad4d24012a949111dec <br />
本章译文最后维护日期：2020-11-30</p>
</blockquote>
<p>如我们所见，伪随机数生成器(PRNG)的输出由其初始状态决定。</p>
<p>一些PRNG的定义指定了如何从一个密钥来生成其初始状态，一般情况下，为加密生成器，需要指定一串字节序列，而对于小型PRNG，通常仅指定一个单词。对于此类可以置种的生成器，我们同一用 <a href="https://rust-random.github.io/rand/rand_core/trait.SeedableRng.html"><code>SeedableRng</code></a> trait 来对其进行形式化处理。。</p>
<h2><a class="header" href="#the-seed-type" id="the-seed-type">The Seed type</a></h2>
<h2><a class="header" href="#种子类型" id="种子类型">种子类型</a></h2>
<p>我们要求所有可置种的RNG需定义一个满足 <code>AsMut&lt;[u8]&gt; + Default + Sized</code>（通常是一个固定 <code>N</code> 的 <code>[u8; N]</code>）的 <a href="https://rust-random.github.io/rand/rand_core/trait.SeedableRng.html#type.Seed"><code>Seed</code></a>类型。
对于非加密型PRNG，我们建议使用 <code>[u8; 12]</code> 或更大；对于加密型PRNG，建议使用 <code>[u8; 32]</code>。</p>
<p>可以通过应用 <a href="https://rust-random.github.io/rand/rand_core/trait.SeedableRng.html#tymethod.from_seed"><code>SeedableRng::from_seed</code></a> 来获得此类建议值，同时直接为PRNG置种。</p>
<h2><a class="header" href="#seeding-from-" id="seeding-from-">Seeding from ...</a></h2>
<h2><a class="header" href="#置种的来源类型" id="置种的来源类型">置种的来源类型...</a></h2>
<h3><a class="header" href="#fresh-entropy" id="fresh-entropy">Fresh entropy</a></h3>
<h3><a class="header" href="#新鲜熵" id="新鲜熵">新鲜熵</a></h3>
<p>使用 <a href="https://rust-random.github.io/rand/rand_core/trait.SeedableRng.html#method.from_entropy"><code>SeedableRng::from_entropy</code></a> 来获取新鲜的种子（直接来自操作系统）是很容易的事儿：</p>
<pre><pre class="playground"><code class="language-rust editable">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use rand::prelude::*;
use rand_chacha::ChaCha20Rng;

let rng = ChaCha20Rng::from_entropy();
<span class="boring">}
</span></code></pre></pre>
<p>请注意，这需要 <code>rand_core</code>模块启用 <code>getrandom</code>特性。</p>
<h3><a class="header" href="#another-rng" id="another-rng">Another RNG</a></h3>
<h3><a class="header" href="#其他的rng" id="其他的rng">其他的RNG</a></h3>
<p>一个常见的操作是使用一个RNG为另一个RNG提供种子。为此，我们为这种常见的操作提供了一种方便的方法：</p>
<pre><pre class="playground"><code class="language-rust editable">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use rand::prelude::*;
use rand_pcg::Pcg64;

let rng = Pcg64::from_rng(thread_rng());
<span class="boring">}
</span></code></pre></pre>
<p>另一种情况，假设您想保存一个密钥并在以后使用它。为此，你可能需要指定更明确一点：</p>
<pre><pre class="playground"><code class="language-rust editable">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use rand::prelude::*;
use rand_chacha::ChaCha8Rng;

let mut seed: &lt;ChaCha8Rng as SeedableRng&gt;::Seed = Default::default();
thread_rng().fill(&amp;mut seed);
let rng = ChaCha8Rng::from_seed(seed);
<span class="boring">}
</span></code></pre></pre>
<p><strong>必须警告</strong>：一些简单的PRNG，特别是 <a href="https://rust-random.github.io/rand/rand_xorshift/struct.XorShiftRng.html"><code>XorShiftRng</code></a> 使用同一类型的生成器来置种时表现得很糟糕（在这种情况下，Xorshift 会生成一个克隆）。对于加密型PRNG，这不是问题；但对于其他类型的PRNG，仍建议从不同类型的生成器来获取种子。一般情况下，<a href="https://rust-random.github.io/rand/rand_chacha/struct.ChaCha8Rng.html"><code>ChaCha8Rng</code></a> 是种子生成器的最佳选择（但是对于加密用途，更好的选择是通过12轮或更多次的变换）。</p>
<h3><a class="header" href="#a-simple-number" id="a-simple-number">A simple number</a></h3>
<h3><a class="header" href="#简单数字" id="简单数字">简单数字</a></h3>
<p>对于某些应用程序，特别是模拟程序，一般只需要一系列不同的、固定的随机数种子，例如1、2、3等。</p>
<p><a href="https://rust-random.github.io/rand/rand_core/trait.SeedableRng.html#method.seed_from_u64"><code>SeedableRng::seed_from_u64</code></a> 正是为这种用例来设计的。在内部，它使用一个简单的PRNG来补充输入的种子数字中的比特位，同时提供良好的 bit-avalance（所以尽管两个类似的数字输入，如0和1，仍被转换成了非常不同的种子和独立的RNG序列）。</p>
<pre><pre class="playground"><code class="language-rust editable">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use rand::prelude::*;
use rand_pcg::Pcg64;

let rng = Pcg64::seed_from_u64(2);
<span class="boring">}
</span></code></pre></pre>
<p>请注意，64-bit 或位宽更少的数字<strong>是不安全的</strong>，因此不应将其用于加密或赌博游戏等应用场景。</p>
<h3><a class="header" href="#a-string-or-any-hashable-data" id="a-string-or-any-hashable-data">A string, or any hashable data</a></h3>
<h3><a class="header" href="#字符串或哈希数据" id="字符串或哈希数据">字符串或哈希数据</a></h3>
<p>假设让用户输入一个字符串来作为随机数生成器的种子。理想情况下，字符串的所有部分都应该能影响生成器，并且只需对字符串进行很小的更改就可以产生完全独立的生成器序列。</p>
<p>这可以通过使用哈希函数将所有输入数据压缩为一个哈希值，然后使用该值作为生成器种子来实现。<a href="https://github.com/rust-random/seeder/"><code>rand_seeder</code></a> crate 就是为了这个目的而设计的。</p>
<pre><pre class="playground"><code class="language-rust editable">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use rand::prelude::*;
use rand_seeder::{Seeder, SipHasher};
use rand_pcg::Pcg64;

// 使用&quot;stripy zebra&quot;的哈希值生成一个Seeder，然后用这个Seeder生成一个SeedableRng类型的RNG。
// 本例生成了为rand_pcg::Pcg64类型的:
let rng: Pcg64 = Seeder::from(&quot;stripy zebra&quot;).make_rng();

// 如果我们想要过程更清晰明确，我们可以首先创建一个SipRng：
let hasher = SipHasher::from(&quot;a sailboat&quot;);
let mut hasher_rng = hasher.into_rng();
// （注意：hasher_rng是一个功能完备的RNG，可以直接使用。）

// 现在，我们使用hasher_rng创建一个种子：
let mut seed: &lt;Pcg64 as SeedableRng&gt;::Seed = Default::default();
hasher_rng.fill(&amp;mut seed);

// 然后从这个种子中创建RNG：
let rng = Pcg64::from_seed(seed);
<span class="boring">}
</span></code></pre></pre>
<p>请注意，<code>rand_seeder</code> 对于加密用法是<strong>不适合的</strong>。它不是<strong>密码哈希器</strong>，对于此类应用程序，必须使用密钥派生函数，如 Argon2。</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        
                            <a rel="prev" href="guide-rngs.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>
                        

                        
                            <a rel="next" href="guide-values.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                
                    <a rel="prev" href="guide-rngs.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a rel="next" href="guide-values.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
                
            </nav>

        </div>

        

        

        

        
        <script type="text/javascript">
            window.playground_copyable = true;
        </script>
        

        

        
        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
        

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        

        

    </body>
</html>
